<template>
  <div id="admin">
    <div class="titleBar">
      <div>指标管理</div>
      <div>
        <el-button
          type="primary"
          @click="(dialogVisible = true), (isAdd = true)"
          >创建指标</el-button
        >
      </div>
    </div>
    <div class="tabBar">
      <div></div>
      <div>
        <el-table
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          border
          default-expand-all
        >
          <el-table-column type="index" width="50" fixed align="center">
          </el-table-column>
          <el-table-column prop="title" label="标题" width="180" align="center">
          </el-table-column>
          <el-table-column
            prop="timeon"
            label="开始时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="endtime"
            label="结束时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column label="是否启用" width="180" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" type="info" v-if="scope.row.type == 1"
                >已截止</el-tag
              >
              <el-tag
                size="mini"
                type=""
                v-if="scope.row.type == 0"
                effect="dark"
                >运行中</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="number" label="提交人数" align="center">
          </el-table-column>
          <el-table-column prop="scope" label="总分" align="center">
          </el-table-column>
          <el-table-column
            label="编辑"
            width="120"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="ubutton">
                <el-button @click="(dialogVisible2 = true), editor(scope.row)"
                  >编辑内容</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="操作"
            width="130"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="primary"
                icon="el-icon-edit"
                circle
                size="small"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="small"
                @click="deleteRating(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表单 -->
    <div class="el-dialog1">
      <el-dialog
        :title="isAdd ? '新增问卷' : '修改问卷'"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-form"
        >
          <el-form-item label="标题" prop="title">
            <el-input size="mini" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="timeon">
            <el-col :span="11">
              <el-date-picker
                v-model="form.timeon"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="截止时间" prop="endtime">
            <el-col :span="11">
              <el-date-picker
                v-model="form.endtime"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="备注" prop="type">
            <el-input size="mini" v-model="form.type"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">取 消</el-button>
          <el-button type="primary" @click="addRating('form', form)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <div class="created_form">
      <el-dialog
        title="创建内容"
        :visible.sync="dialogVisible2"
        width="30%"
        :before-close="handleClose2"
        fullscreen
      >
        <div class="work" v-for="(item, index) in question" :key="index">
          <div class="work_title">
            <div class="index">{{ index + 1 }}.</div>
            <div>
              <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="item.textarea"
              >
              </el-input>
            </div>
            <div class="score_text">得分</div>
            <div class="score">
              <el-input-number
                v-model="item.scope"
                controls-position="right"
                @change="handleChange"
                :min="1"
                :max="50"
              ></el-input-number>
            </div>
            <div class="switch_button">
              <div style="margin-bottom: 8px">是否需要上传附件</div>
              <div>
                <el-switch
                  @change="switchFuJian(item, index)"
                  v-model="item.annex"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </div>
            </div>
          </div>
          <div class="word_button">
            <div>
              <el-button type="text" @click="new_word(index)"
                >在此题后插入新题</el-button
              >
            </div>
            <div>
              <el-button
                icon="el-icon-delete"
                size="mini"
                @click="delete_word(index, item)"
                >删除</el-button
              >
            </div>
          </div>
        </div>
        <div class="reset">
          <el-button type="info" plain>重置</el-button>
        </div>
        <div class="tab_bottom">
          <div>
            <div>{{ sum }}</div>
            <div>总分</div>
          </div>
          <div>
            <el-button type="primary" @click="pushWork">提交</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  updatawenjuan,
  deletwenjuan,
  allneirong,
  addneirong,
  addwenjuan,
  allwenjuan,
  deletneirong,
} from "@/api/rating";

export default {
  watch: {},

  data() {
    return {
      form: {
        title: "",
        type: "",
        timeon: "",
        endtime: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        timeon: [
          {
            type: "string",
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        endtime: [
          {
            type: "string",
            required: true,
            message: "请选择截止时间",
            trigger: "change",
          },
        ],
      },
      isAdd: true,
      tableData: [],
      //弹窗
      dialogVisible: false,
      dialogVisible2: false,
      //子菜单回显
      levels: "",
      num: 1,
      question: [
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
      ],

      question2: [
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
        {
          textarea: "",
          scope: 20,
        },
      ],
      //总分
      sum: 100,

      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },

      //问卷id
      question_id: "",
    };
  },

  created() {
    this.init();
  },

  methods: {
    init() {
      this.getRating();
    },

    //获取问卷
    getRating() {
      allwenjuan().then((res) => {
        this.tableData = res.data.reverse();
      });
    },

    //新增问卷
    addRating(form, data) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            addwenjuan(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$refs[form].resetFields();
                this.question = this.question2;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          } else {
            updatawenjuan(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$refs[form].resetFields();
                this.question = this.question2;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    //删除菜单
    deleteRating(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, "此操作将永久删除 "),
          h("i", { style: "color: teal" }, row.name),
          h("span", null, "评分表"),
          h(
            "span",
            { style: "color: #F56C6C" },
            "（如果该表已创建评分表，将一同删除）"
          ),
          h("span", null, "，是否继续？"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = {
            id: row.id,
          };
          deletwenjuan(id).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.init();
            } else {
              this.$message({
                type: "danger",
                message: "发生错误无法删除",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //关闭弹窗回调
    handleClose(done) {
      this.$confirm("你还未提交信息，确认关闭？")
        .then((_) => {
          this.$refs.form.resetFields();
          done();
        })
        .catch((_) => {});
    },

    handleClose2(done, a) {
      this.$confirm("你还未提交信息，确认关闭？")
        .then((_) => {
          done();
          this.question = this.question2;
        })
        .catch((_) => {});
    },

    //清空表单
    resetForm(form) {
      this.dialogVisible = false;
      this.$refs[form].resetFields();
      this.question = this.question2;
    },

    //编辑按钮
    handleClick(row) {
      this.isAdd = false;
      this.dialogVisible = true;
      this.$nextTick(function () {
        this.form = Object.assign({}, row);
      });
    },

    handleChange(value) {
      this.allScore();
    },

    //新增填写
    new_word(index) {
      let inp = {
        textarea: "",
        scope: 20,
      };
      this.question.splice(index + 1, 0, inp);
      this.$notify({
        title: "成功",
        message: "新增填写成功",
        type: "success",
      });
      let sum = 0;
      for (let i = 0; i < this.question.length; i++) {
        const element = this.question[i].scope;
        sum += element;
      }
      this.sum = sum;
    },

    //删除当前填写
    delete_word(index, item) {
      let n = this.question.length;
      if (n == 1) {
        this.$notify.error({
          title: "不能删除",
          message: "至少保留一个输入框",
        });
      } else {
        if (item.hasOwnProperty("wjid")) {
          let id = {
            question: [{ wjid: item.wjid }],
          };
          deletneirong(id).then((res) => {
            if (res.code == 0) {
              this.question.splice(index, 1);
              this.allScore();
              // this.$message({
              //   type: "success",
              //   message: "删除成功",
              //   center: true,
              //   showClose: true,
              // });
              var title_index = index + 1;
              const h = this.$createElement;
              this.$notify({
                title: "删除成功",
                message: h("p", null, [
                  h("i", null, "您已经删除第 "),
                  h("i", { style: "color: red" }, title_index),
                  h("i", null, "题及其内容"),
                ]),
                type: "warning",
                position: "bottom-right",
              });
            } else {
              this.$message({
                type: "error",
                message: "出错了，请联系管理员！！！",
                center: true,
                showClose: true,
              });
            }
          });
        } else {
          this.question.splice(index, 1);
          this.allScore();
          // this.$message({
          //   type: "success",
          //   message: "删除成功",
          //   center: true,
          //   showClose: true,
          // });
          var title_index = index + 1;
          const h = this.$createElement;
          this.$notify({
            title: "删除成功",
            message: h("p", null, [
              h("i", null, "您已经删除第 "),
              h("i", { style: "color: red" }, title_index),
              h("i", null, "题及其内容"),
            ]),
            type: "warning",
            position: "bottom-right",
          });
        }
      }
    },

    allScore() {
      let a = this.question;
      var sum = 0;
      a.forEach((element) => {
        sum += element.scope;
      });
      this.sum = sum;
    },

    //编辑内容
    editor(row) {
      let id = {
        id: row.id,
      };
      this.question_id = id;
      allneirong(id).then((res) => {
        if (res.data.length !== 0) {
          let sum = 0;
          for (let i = 0; i < res.data.length; i++) {
            const element = res.data[i].scope;
            sum += element;
          }
          this.sum = sum;
          this.question = res.data;
        }
      });
    },

    // 提交问卷
    pushWork() {
      let id = this.question_id.id;
      let question = [];
      this.question.forEach((element) => {
        element.id = id;
        question.push(element);
      });
      let qt = {
        question: question,
      };
      addneirong(qt).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "创建成功",
            center: true,
            showClose: true,
          });
          this.dialogVisible2 = false;
        }
      });
    },

    //是否需要上传附件开关
    switchFuJian(data, index) {
      this.question[index] = data;
    },
  },
};
</script>

<style lang="scss" scoped>
#admin {
  height: calc(100vh - 84px);
  width: 100%;
  background-color: #ffffff;
  padding: 0 20px 20px 20px;
  line-height: auto;

  .titleBar {
    border-bottom: 1px solid #0000002e;
    height: 70px;
    line-height: 70px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .tabBar {
    height: calc(100vh - 174px);
    overflow: auto;

    .ubutton {
      ::v-deep .el-button {
        padding: 12px 8px;
      }
    }

    .icon-picker-selected > i {
      font-size: 16px;
    }
  }

  .created_form {
    ::v-deep .el-dialog__body {
      height: calc(100vh - 54px);
      overflow: auto;
    }

    .work {
      border-bottom: 1px solid #cdcdcd;
      width: calc(60vw + 158px);
      margin-bottom: 50px;
      .work_title {
        display: flex;
        margin: 0;
        align-items: center;

        .index {
          margin-right: 10px;
          font-size: 18px;
          font-weight: 500;
        }

        .score_text {
          margin-left: 10px;
          margin-right: 10px;
          font-weight: 500;
        }
        .score {
          ::v-deep .el-input-number {
            width: 90px;
          }
        }

        ::v-deep .el-textarea__inner {
          width: 40vw !important;
          min-height: 80px !important;
        }

        .switch_button {
          width: 112px;
          margin-left: 38px;
        }
      }

      .word_button {
        height: 100px;
        width: calc(40vw + 165px);
        padding-left: 25.02px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        :nth-child(2) {
          align-self: flex-end;
          margin-bottom: 5px;
        }
      }
    }

    .reset {
      width: calc(40vw + 165px);
      margin-bottom: 50px;
      text-align: center;
    }

    .tab_bottom {
      position: fixed;
      bottom: 0;
      background-color: #f3f3f3;
      left: 0;
      height: 50px;
      width: 100%;
      border-top: 1px solid #a1a1a12e;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;

      :nth-child(1) {
        // background-color: darkgoldenrod;
        div:nth-child(1) {
          font-size: 20px;
          margin: 0 auto;
          color: #ce0000;
        }
        :nth-child(2) {
          font-size: 5px;
          margin: 0 auto;
        }
      }
    }
  }

  .el-dialog1 {
    ::v-deep .el-dialog {
      margin-top: 8vh !important;
      width: 35% !important;
      min-width: 450px !important;
    }
  }
}

::v-deep .el-col-2 {
  width: 5px;
  margin-left: 2px;
  margin-right: 2px;
}
</style>